<template>
    <div>
        <div>数据规范定义</div>
        <el-container>
            <el-header>
                <el-input size="small" style="width:50%; margin-right:10px;" placeholder=""></el-input>
                <el-button size="small" type="primary">模糊查找</el-button>
                <el-button size="small" type="primary">管理数据规范</el-button>
            </el-header>
            <el-main >
                <div class="o-dor">
                    <el-row>
                        <el-col :span="6">
                            <vxe-table
                            show-overflow
                            ref="xTree1"
                            size="mini"
                            row-id="type"
                            :height="(jsgs||barcode?'500':'300')+'px'"
                            :show-header="false"
                            :radio-config="{labelField: 'title',checkRowKey:'selectType'}"
                            @radio-change="radioChangeEvent"
                            :data="DS"
                            >
                                <vxe-column type="radio"></vxe-column>
                            </vxe-table>
                        </el-col>
                        <el-col :span="18" v-show="!jsgs&&!barcode">
                            <vxe-table
                            border
                            size="mini"
                            ref="xTree2"
                            row-id="RegisterID"
                            height="100%"
                            :align="null"
                            :radio-config="{labelField: 'ComponentName', trigger: 'row',checkRowKey: defaultSelecteRow,reserve:true }"
                            @cell-click="tableClick"
                            :data="DSSelect"         >
                            <vxe-column type="seq" width="60"></vxe-column>
                            <vxe-column type="radio" title="数据规范列表"></vxe-column>
                          </vxe-table>
                        </el-col>
                        <el-col :span="18" v-show="jsgs">
                            <el-row>
                                <el-col :span="12" v-show="jsgs"><vxe-table
                                    border
                                    size="mini"
                                    ref="fields"
                                    :height="(jsgs||barcode?'500':'300')+'px'"
                                    @cell-click="fieldsDataClick"
                                    :data="fieldsData" >
                                    <vxe-column field="fieldDispName"  title="字段别名"></vxe-column>
                                    <vxe-column field="fieldName" width="80" title="字段名"></vxe-column>
                                  </vxe-table></el-col>
                                <el-col :span="12" v-show="jsgs">
                                    <div class="o-p">
                                        <el-button type="primary" size="small" plain @click="DSData['formula']=DSData['formula']+' + '">+</el-button>
                                        <el-button type="primary" size="small" plain @click="DSData['formula']=DSData['formula']+' - '">-</el-button>
                                        <el-button type="primary" size="small" plain @click="DSData['formula']=DSData['formula']+' * '">*</el-button>
                                        <el-button type="primary" size="small" plain @click="DSData['formula']=DSData['formula']+' / '">/</el-button>
                                    </div>
                                    <el-input type="textarea" :autosize="{ minRows: 12, maxRows: 12 }" placeholder="请输入内容" v-model="DSData['formula']"></el-input>
                                    <el-radio-group v-model="DSData['one']">
                                        <el-radio :label="0">总是计算</el-radio>
                                        <el-radio :label="1">计算一次</el-radio>
                                    </el-radio-group>
                                </el-col>
                            </el-row>
                        </el-col>
                      <el-col :span="18" v-if="barcode">
                        <vxe-form
                            title-colon
                            title-align="right"
                            title-width="120"
                            :data="DSData">
                          <vxe-form-gather span="12">
                            <vxe-form-item title="解码后字段数" field="count" span="24" :item-render="{}">
                              <template #default="{ data }">
                                <vxe-select v-model="data.count" placeholder="请选择数量" clearable>
                                  <vxe-option v-for="num in 10" :key="num" :value="num" :label="`${num}`"></vxe-option>
                                </vxe-select>
                              </template>
                            </vxe-form-item>
                            <vxe-form-item title="解码分隔符" field="separator" span="24" :item-render="{name: '$input'}"></vxe-form-item>
                            <vxe-form-item title="默认取数位置" field="size" span="24" :item-render="{}">
                              <template #default="{ data }">
                                <vxe-select v-model="data.size" placeholder="请选择位置" clearable>
                                  <vxe-option v-for="num in 10" :key="num" :value="num-1" :label="`${num}`"></vxe-option>
                                </vxe-select>
                              </template>
                            </vxe-form-item>
                            <vxe-form-item title="扫前检查类型" field="required.type" span="12" :item-render="{}" >
                              <template #default="{ data }">
                                <vxe-select v-model="data.required.type" clearable>
                                  <vxe-option value="scandata" label="表单数据"></vxe-option>
                                  <vxe-option value="barcode" label="解码数据"></vxe-option>
                                </vxe-select>
                              </template>
                            </vxe-form-item>
                            <vxe-form-item title="扫前检查字段" field="required" span="12" :item-render="{}" title-overflow="title">
                              <template #default="{data}">
                                <vxe-select v-model="data.required.field" >
                                  <vxe-option v-for="(it,index) in fieldsData" :value="it.fieldName" :label="it.fieldDispName" :key="index"></vxe-option>
                                </vxe-select>
                              </template>
                            </vxe-form-item>
                            <vxe-form-item title="扫后检查字段" field="check" span="12" :item-render="{}" title-overflow="title">
                              <template #default="{data}">
                                <vxe-select v-model="data.check" clearable>
                                  <vxe-option v-for="(it,index) in fieldsData" :value="it.fieldName" :label="it.fieldDispName" :key="index"></vxe-option>
                                </vxe-select>
                              </template>
                            </vxe-form-item>
                            <vxe-form-item title=""  span="24" :item-render="{}">
                              <template #default="{ data }">
                                <div style="display: flow-root;">解码对应字段<el-button style="float: right" size="small" type="primary"  @click="barcodetofield.insertAt({},-1)">新增</el-button></div>
                                <vxe-table
                                    border
                                    size="mini"
                                    ref="barcodetofield"
                                    height="300px"
                                    :data="DSData.tofield" >
                                  <vxe-column field="site"  title="解码后位置">
                                    <template #default="{row}">
                                      <vxe-select v-model="row.site" >
                                        <vxe-option v-for="num in data.count" :value="num" :label="'位置'+num" :key="num"></vxe-option>
                                      </vxe-select>
                                    </template>
                                  </vxe-column>
                                  <vxe-column field="field"  title="对应字段">
                                    <template #default="{row}">
                                      <vxe-select v-model="row.field" >
                                        <vxe-option v-for="(it,index) in fieldsData" :value="it.fieldName" :label="it.fieldDispName" :key="index"></vxe-option>
                                      </vxe-select>
                                    </template>
                                  </vxe-column>
                                  <vxe-column   title="操作">
                                    <template #default="{row}">
                                      <el-button size="small" type="primary"  @click="barcodetofield.remove(row)">删除</el-button>
                                    </template>
                                  </vxe-column>
                                </vxe-table>
                              </template>
                            </vxe-form-item>

                          </vxe-form-gather>
                          <vxe-form-gather span="12">
                            <vxe-form-item title="扫码数据存新表" field="totable" span="12" :item-render="{}" title-overflow="title">
                              <template #default="{data}">
                                <vxe-select v-model="data.totable.table" clearable @change="filterSelect">
                                  <vxe-option v-for="(it,index) in TBData" :visible="it.tableType===1"  :value="it.tableName" :label="it.tableDispName" :key="index"></vxe-option>
                                </vxe-select>
                              </template>
                            </vxe-form-item>
                            <vxe-form-item title=""  span="24" :item-render="{}">
                              <template #default="{ data }">
                                <div style="display: flow-root;">保存字段<el-button style="float: right" size="small" type="primary"  @click="barcodetotable.insertAt({},-1)">新增</el-button></div>
                                <vxe-table
                                    border
                                    size="mini"
                                    ref="barcodetotable"
                                    height="300px"
                                    :data="DSData.totable.field" >
                                  <vxe-column  title="字段类型" field="source" >
                                    <template #default="{ row }">
                                      <vxe-select v-model="row.source" clearable>
                                        <vxe-option value="scandata" label="表单数据"></vxe-option>
                                        <vxe-option value="barcode" label="解码数据"></vxe-option>
                                      </vxe-select>
                                    </template>
                                  </vxe-column >
                                  <vxe-column field="site"  title="来源">
                                    <template #default="{row}">
                                      <div v-if="row.source==='barcode'">
                                        <vxe-select v-model="row.site" clearable>
                                          <vxe-option v-for="num in DSData.count" :value="num" :label="'位置'+num" :key="num"></vxe-option>
                                        </vxe-select>
                                      </div>
                                      <div v-else>
                                        <vxe-select v-model="row.from" clearable>
                                            <vxe-optgroup v-for="(its,index) in TBData" :visible="its.tableType===1"  :label="its.tableDispName">
                                              <vxe-option v-for="(it,index) in its.Fields" :value="it.fieldName" :label="it.fieldDispName" :key="index"></vxe-option>
                                            </vxe-optgroup>
                                          </vxe-select>
                                      </div>

                                    </template>
                                  </vxe-column>
                                  <vxe-column field="field"  title="对应字段">
                                    <template #default="{row}">
                                      <vxe-select v-model="row.field" clearable>
                                        <vxe-optgroup v-for="(its,index) in TBData" :visible="its.tableName===data.totable.table"  :label="its.tableDispName">
                                          <vxe-option v-for="(it,index) in its.Fields" :value="it.fieldName" :label="it.fieldDispName" :key="index"></vxe-option>
                                        </vxe-optgroup>
                                      </vxe-select>
                                    </template>
                                  </vxe-column>
                                  <vxe-column   title="操作">
                                    <template #default="{row}">
                                      <el-button size="small" type="primary"  @click="barcodetotable.remove(row)">删除</el-button>
                                    </template>
                                  </vxe-column>
                                </vxe-table>
                              </template>
                            </vxe-form-item>
                            <vxe-form-item title="唯一字段" title-width="80" field="totable" span="24" :item-render="{}" title-overflow="title">
                              <template #default="{data}">
                                <vxe-select v-model="data.totable.filter" clearable multiple transfer ref="select2"  placeholder="可多选">
                                  <vxe-optgroup v-for="(its,index) in TBData.filter(item=>item.tableName===data.totable.table)"  :label="its.tableDispName">
                                    <vxe-option v-for="(it,index) in its.Fields" :value="it.fieldName" :label="it.fieldDispName" :key="index"></vxe-option>
                                  </vxe-optgroup>
                                </vxe-select>
                              </template>
                            </vxe-form-item>
                            <vxe-form-item title="合计字段"  title-width="80" field="totable" span="12" :item-render="{}" title-overflow="title">
                              <template #default="{data}">
                                <vxe-select v-model="data.totable.sum" clearable transfer ref="select2">
                                  <vxe-optgroup v-for="(its,index) in TBData.filter(item=>item.tableName===data.totable.table)"  :label="its.tableDispName">
                                    <vxe-option v-for="(it,index) in its.Fields" :value="it.fieldName" :label="it.fieldDispName" :key="index"></vxe-option>
                                  </vxe-optgroup>
                                </vxe-select>
                              </template>
                            </vxe-form-item>




                          </vxe-form-gather>
                        </vxe-form>

                        <el-row>
                          <el-col :span="12" >
                           </el-col>
                        </el-row>
                      </el-col>
                    </el-row>
                </div>
                <el-row>
                    <el-col :sapn="24" style="display: flex; justify-content: space-between;align-items: center;">
                        <div>
                            <el-checkbox v-if="type===3" v-model="expandType.single" label="单选" size="large" />
                        </div>
                        <div>
                            <el-button size="small" @click="submit(2)">确定</el-button>
                            <el-button size="small" @click="submit(1)">取消</el-button>
                            <el-button size="small" @click="submit(0)">清除</el-button>
                        </div>
                    </el-col>
                </el-row>
                <el-tabs v-show="!jsgs&&!barcode" type="border-card">
                    <el-tab-pane label="筛选条件">
                        <el-input
                            v-model="filterExpr"
                            style="width: 70%;"
                            resize="none"
                            rows="4"
                            type="textarea"
                        />
                        <div class="el-rgb" style="height: 94px;width:94px; margin: 0 10px;" @click="clickSchoose">选择</div>
                    </el-tab-pane>
                    <el-tab-pane label="关联填充">
                            <el-input
                                v-model="componentDatas"
                                style="width: 70%;"
                                resize="none"
                                rows="4"
                                type="textarea"
                            />
                            <div class="el-rgb" style="height: 94px;width:94px; margin: 0 10px;" @click="fillDataClick">选择</div>
                    </el-tab-pane>
                </el-tabs>
            </el-main>
        </el-container>
        <el-dialog
            v-model="Schoose"
            title="过滤条件设置"
            width="60%"
        >   
          <filterchoose ref="choose" :LData="DSCDate" :RData="TableData" :Filter="filterExpr" @submit="Schooseshow"></filterchoose>
        </el-dialog>
        <el-dialog
            v-model="showfillpbut"
            title="过滤条件设置"
            width="60%"
        > 
            <fillpopup :LData="fillLData" :RData="fillRData" @submit="fillpbut"></fillpopup>
        </el-dialog>
    </div>
</template>

<script>
import {onBeforeMount, reactive, ref, toRefs,onMounted} from "vue"
import {getDS, getDSInfo} from "/@/api/linkoo/templates/specification"
import XEUtils from "xe-utils"
import {ElMessage} from 'element-plus'
import filterchoose from './filterchoose.vue'
import fillpopup from './fillpopup.vue'

export default {
    props: ['TFData', 'FillData', 'FieldRow'],
    emits:["submitew",],
    components:{filterchoose,fillpopup},
    setup(props,ctx) {
        let xTree1 = ref(null)
        let xTree2 = ref(null)
        let barcodetofield = ref(null)
        let barcodetotable = ref(null)
        let select1 = ref(null)
        let select2 = ref(null)
        let state = reactive({
            DSSelect: [],
            expandType: {},
            DSdata: [],
            DSCDate: [],
            DSData: {},
          barcodeData: {"count": 1,"separator": "|",size:1,"tofield": [],"totable":{"table": "","field": [],"filter": [],"sum": ""},"check": "","sumInfo": "","required":{"type": "","field": ""}},
            TableData: [],
            showfillpbut: false,
            fillRData: [],
            filterExpr: '',
            fieldsData: [],
          TBData: [],
            type:0,
            jscs: 0,
            Schoose: false,
            jsgs: false,
          barcode: false,
            componentDatas: '',
            defaultSelecteRow: 0,
            fillLData: [],
          DS: [{ type: 0, title: '默认规范' }, { type: 1, title: '下拉框' }, { type: 2, title: '树型框' }, {type: 3,title: '列表框'}, { type: 4, title: '选择框' }, { type: 5, title: '自动编号' },{ type:6, title: '内部接口' },{ type:7, title: '外部接口' },{type:8,title:'扫码'},{type:9,title:'计算公式'},{type:10,title:'明细扩展表'}]

        })
        onBeforeMount(()=>{
          state.TBData=XEUtils.clone(props.TFData,true)
             setTimeout(()=>{
               const rows=xTree1.value.getTableData().fullData
               XEUtils.arrayEach(rows,row=>{
                 if(row.type===props.FieldRow.componentType)
                 {
                   xTree1.value.setRadioRow(row)
                   radioChangeEvent()
                 }
               })
             },300)


            getComponent()
            getDefaultTable()
                if(9===props.FieldRow.componentType){
                    if(props.FieldRow.componentFieldName === ''){
                        state.DSData =  {formula:'',one:0}
                    }else  if(props.FieldRow.componentFieldName[0] === '{'){
                        state.DSData =  JSON.parse(props.FieldRow.componentFieldName)
                    }else {
                        state.DSData =  {formula:'',one:0}
                        state.DSData['formula']=props.FieldRow.componentFieldName
                    }
                } else if(8===props.FieldRow.componentType)  {
                state.DSData =XEUtils.merge(state.barcodeData,  JSON.parse(props.FieldRow.componentFieldName))
              }else {
                    state.DSData = props.FieldRow.componentFieldName === '' ? {} : JSON.parse(props.FieldRow.componentFieldName)
                }

          state.filterExpr = props.FieldRow.componentFilterExpr
            showdata()
          // console.log(state.DSData)
          setTimeout(()=>{
            tableClick({
              row: {
                ComponentType: props.FieldRow.componentType,
                ComponentID: props.FieldRow.componentID,
                RegisterID: state.defaultSelecteRow
              }
            })
          },300)

        })
        const getComponent = ()=>{
            getDS(0).then(res => {
              XEUtils.arrayEach(res.data.list, (item, key) => {
                if (props.FieldRow.componentType === item.ComponentType && props.FieldRow.componentID === item.ComponentID) {
                  state.defaultSelecteRow = item.RegisterID
                }
              })
              state.DSdata = res.data.list
              state.DSSelect = res.data.list
            })
        }
        const radioChangeEvent=()=> {
            let selectRow = xTree1.value.getRadioRecord()
            state.DSSelect = state.DSdata.filter(item => item.ComponentType === selectRow['type'])

            state.type=selectRow['type']
            if(selectRow['type']===9){
                state.jsgs=true
            }else {
                state.jsgs=false
            }
            if(selectRow['type']===8){
              state.DSData =props.FieldRow.componentFieldName===''?state.barcodeData:XEUtils.toStringJSON(props.FieldRow.componentFieldName)
                  state.barcode=true
            }else {
                state.barcode=false
            }
        }
        let choose=ref(null)
        const tableClick = ({row})=>{
            state.fillLData = [{ label: '', value: '' }]
            state.DSCDate = []
            if (state.defaultSelecteRow !== row.RegisterID) {
                state.filterExpr = ''
                state.componentDatas = ''
                state.DSData = {}
            }

            getDSInfo(row.ComponentType, row.ComponentID).then(res => {
                if ([3,6].includes(row.ComponentType)){
                res.data.table.forEach(table => {
                    let tb = { title: '[' + table.tableDispName + ']', name: table.tableName, children: [], isF: false }
                    let fields = res.data.fullfield.filter(item => item.TableName === table.tableName)
                    tb.children = fields.map((rows, index) => {
                    return { name: rows.fieldName, title: rows.FieldExpr, isF: true }
                    })
                    state.DSCDate.push(tb)
                })
                res.data.selectfield.forEach(row => {
                    state.fillLData.push({ label: row.fieldDispName, value: row.fieldDispName })
                })
                }

            })
        }
        const showdata = ()=>{
            state.fieldsData=props.FillData//.filter(item=>item.fieldName!==props.FieldRow.fieldName)
            state.type=props.FieldRow.componentType
            state.expandType=props.FieldRow.expandType?JSON.parse(props.FieldRow.expandType):''

            if(props.FieldRow.componentType===9){
                state.defaultSelecteRow=9
                state.jsgs=true
                return}
            setTimeout(() => {
                let data = []
                XEUtils.objectEach(state.DSData, (item, key) => {
                let field = XEUtils.find(props.FillData, it => it.fieldName === key) // null
                  if(field){
                    data.push(field.fieldDispName + '->值为: ' + item.v)
                  }

                })
                state.componentDatas = data.join('\n')
            }, 80)
        }
        const fieldsDataClick=({row})=>{state.DSData['formula']+=row.fieldName+' '}
        const submit=(status) =>{
            let selectRow = xTree2.value.getRadioRecord()
            let types = xTree1.value.getRadioRecord()
          if(types&&types.type===8){
            let data=XEUtils.clone(barcodetofield.value.getTableData().fullData,true)
            state.DSData.tofield=data.map(row=>{
              delete row['_X_ROW_KEY'];return row
            })
            data=XEUtils.clone(barcodetotable.value.getTableData().fullData,true)
            state.DSData.totable.field=data.map(row=>{
              delete row['_X_ROW_KEY'];return row
            })
          }
          if(types){
            let records = {
                expandType:JSON.stringify(state.expandType),
                componentFieldID:status>0?selectRow!==null?selectRow['ComponentName']:(types['type']===10?"明细扩展":types['type']===8?"扫码":types['type']===9?"计算公式":""):"",
                componentFieldName:status>0?JSON.stringify(state.DSData):"",
                componentFilterExpr:status>0?state.filterExpr:"",
                componentID:status>0?selectRow!==null?selectRow['ComponentID']:null:null,
                componentType:status>0?selectRow!==null?selectRow['ComponentType']:types['type']:null
            }
            if(records.componentType===9&&records.componentFieldName.indexOf(props.FieldRow.fieldName)>-1){
                ElMessage({
                    type: 'error',
                    message: '公式内不能包含自己!',
                })
            return
            }
            console.log({ data: records,status:status });
            ctx.emit('submitew', { data: records,status:status })
          }else{
            ctx.emit('submitew',{ data: {},status:status })
          }
            
        }
        const clickSchoose=()=>{state.Schoose=true }
        const Schooseshow=({ filterText, update })=> {
            if (update) {
                state.filterExpr = filterText
            }
            state.Schoose = false
        }
        const getDefaultTable = ()=>{
            state.TableData = []
            props.TFData.forEach(table => {
                let tb = { title: '[' + table.tableDispName + ']', name: table.tableName, children: [], isF: false }
                tb.children = table.children.map((row, index) => {
                return { name: row.fieldName, title: '{' + tb.title + '.[' + row.fieldDispName + ']}', isF: true }
                })
                state.TableData.push(tb)
            })
        }
        const fillDataClick=()=> {
        state.fillRData = []
        props.FillData.forEach(row => {
            state.fillRData.push({
            name: row.fieldName,
            title: row.fieldDispName,
            v: state.DSData[row.fieldName] === undefined ? '' : state.DSData[row.fieldName].v,
            t: state.DSData[row.fieldName] === undefined ? '' : state.DSData[row.fieldName].t
            })
        })
        state.showfillpbut = true
        }
        const fillpbut=({ data, update })=> {
            state.showfillpbut = false
            if (update) {
                state.DSData = data
                console.log(state.DSData);
                showdata()
            }
        }
        const filterSelect=()=> {
        select1.value.refreshOption();select2.value.refreshOption();
        }
        return{
            xTree1,
            xTree2,
            choose,select1,select2
            ,...toRefs(state)
            ,radioChangeEvent,
          barcodetofield,barcodetotable,
            getComponent,filterSelect,
            tableClick,
            fieldsDataClick,
            fillDataClick,
            showdata,
            submit,
            clickSchoose,
            Schooseshow,
            getDefaultTable,
            fillpbut
        }
    }
}
</script>

<style scoped>
    .el-header{
        margin:10px 0;
        padding: 0;
        height: auto;
    }
.el-main{
    margin: 0;
    padding: 0;
}
.o-dor{
    border: 1px solid #d2d2d2;        
}
.o-p{
    padding: 5px;
}
.el-rgb{
    display: inline-block;
    background-color: rgba(63, 142, 239, 0.845);
    border: 1px solid rgba(63, 142, 239, 0.845);
    border-radius: 5px;
    text-align: center;
    line-height: 95px;
    color: aliceblue;
}
</style>